package com.lsz.intelligentflowerwatering.viewmodel

import android.annotation.SuppressLint
import android.app.Application
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanResult
import android.content.Context
import android.location.LocationManager
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import com.espressif.provisioning.DeviceConnectionEvent
import com.espressif.provisioning.ESPConstants
import com.espressif.provisioning.ESPProvisionManager
import com.espressif.provisioning.listeners.BleScanListener
import com.espressif.provisioning.listeners.ResponseListener
import com.lsz.intelligentflowerwatering.bean.BleDevice
import com.lsz.intelligentflowerwatering.ui.tag
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

sealed class BleState {
    object ScanBegin : BleState()
    object ScanEnd : BleState()
    object ScanFail : BleState()
    object ConnectBegin : BleState()
    object ConnectEnd : BleState()
    object ConnectFail : BleState()
    object DisConnect : BleState()
}

@SuppressLint("MissingPermission")
class BleViewModel(application: Application) : AndroidViewModel(application) {
    var bleState: BleState by mutableStateOf(BleState.ScanEnd)

    val bleDeviceList = mutableStateListOf<BleDevice>()

//    val bleList = mutableStateListOf<String>("123","53456")

    private var provisionManager = ESPProvisionManager.getInstance(null)


    val bluetoothManager: BluetoothManager =
        application.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
//    private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter

    //定位相关
    val locationManager = application.getSystemService(Context.LOCATION_SERVICE) as LocationManager

    var pop = "abcd1234"

    init {
        EventBus.getDefault().register(this)
    }

    override fun onCleared() {
        super.onCleared()
        EventBus.getDefault().unregister(this)
    }

    fun bleScanStart() {
//        if (bluetoothAdapter.isEnabled && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Log.i(MainViewModel.tag, "扫描中！")
            bleDeviceList.clear()
            bleState = BleState.ScanBegin
            provisionManager.searchBleEspDevices("", object : BleScanListener {
                override fun scanStartFailed() {
                    Log.i("BleViewModel", "scanStartFailed")
                    bleState = BleState.ScanFail
                }

                override fun onPeripheralFound(device: BluetoothDevice, scanResult: ScanResult) {
                    Log.i(MainViewModel.tag, "扫描到设备:${device.name}")
                    val temp = bleDeviceList.find { it.bluetoothDevice == device }
                    if (temp == null) {
                        bleState = BleState.ScanBegin
                        val serviceUuid = scanResult.scanRecord?.serviceUuids?.get(0).toString()
                        bleDeviceList.add(BleDevice(device.name, device, serviceUuid))
                    }
                }

                override fun scanCompleted() {
                    Log.i("BleViewModel", "scanCompleted")
                    bleState = BleState.ScanEnd
                    bleDeviceList.forEach { println(it.bluetoothDevice.name) }
                }

                override fun onFailure(e: Exception?) {
                    Log.i("BleViewModel", "onFailure")
                    bleState = BleState.ScanFail
                }
            })
//        }else{
//            Log.i(MainViewModel.tag,"未授权")
//        }

    }

    /**
     * 停止扫描设备
     */
    private fun bleScanStop() {
        bleState = BleState.ScanEnd
        provisionManager.stopBleScan()
    }

    /**
     * 连接设备
     */
    fun bleConnectDevice(bleDevice: BleDevice) {
        bleScanStop()
        Log.i(tag, bleDevice.toString())
        Log.i(tag, provisionManager.toString())

        provisionManager.espDevice.connectBLEDevice(
            bleDevice.bluetoothDevice,
            bleDevice.primaryServiceUuid
        )
        bleState = BleState.ConnectBegin
        Log.i(tag, bleDevice.name)
    }

    /**
     * 初始化对话
     */
    private fun initSession() {
        provisionManager.espDevice.proofOfPossession = pop
        provisionManager.espDevice.userName = "wifiprov"
        provisionManager.espDevice.initSession(object : ResponseListener {
            override fun onSuccess(returnData: ByteArray?) {
                Log.i("BleViewModel", "onSuccess")
            }

            override fun onFailure(e: Exception) {
                Log.i("BleViewModel", "initSession onFailure")
            }
        })
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: DeviceConnectionEvent) {
        Log.i("BleViewModel", "事件：${event.eventType}")
        when (event.eventType) {
            ESPConstants.EVENT_DEVICE_CONNECTED -> {
                Log.i("BleViewModel", "蓝牙连接成功")
                initSession()
//                navController?.navigate(MainScreenRoute.WifiScan.route)
                bleState = BleState.ConnectEnd
            }
            ESPConstants.EVENT_DEVICE_DISCONNECTED -> {
                Log.i("BleViewModel", "蓝牙连接断开")
//                navController?.popBackStack(MainScreenRoute.BleScan.route, false)
                bleState = BleState.DisConnect
            }
            ESPConstants.EVENT_DEVICE_CONNECTION_FAILED -> {
                Log.i("BleViewModel", "蓝牙连接出错")
                bleState = BleState.ConnectFail
            }
        }
    }
}